import { defineStore } from 'pinia'
import { authConfig } from '@/config'
import { login as loginApi } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    isAuthenticated: false,
    user: null,
    token: null,
    mqttConfig: null
  }),
  
  getters: {
    isLoggedIn: (state) => state.isAuthenticated,
    userInfo: (state) => state.user,
    authToken: (state) => state.token
  },
  
  actions: {
    async login(username, password) {
      try {
        // 调用登录API
        const response = await loginApi({
          username,
          password,
          flag: 1
        })
        
        // 现在response包含code、data、message，实际数据在response.data中
        if (response && response.code === 0 && response.data) {
          this.isAuthenticated = true
          
          // 保存token
          this.token = response.data.access_token
          
          // 保存用户信息
          this.user = {
            username: response.data.username,
            userId: response.data.user_id,
            workspaceId: response.data.workspace_id,
            userType: response.data.user_type
          }
          
          // 保存MQTT配置
          this.mqttConfig = {
            username: response.data.mqtt_username,
            password: response.data.mqtt_password,
            address: response.data.mqtt_addr
          }
          
          // 存储到localStorage
          localStorage.setItem(authConfig.tokenKey, this.token)
          localStorage.setItem('user_info', JSON.stringify(this.user))
          localStorage.setItem('mqtt_config', JSON.stringify(this.mqttConfig))
          
          return { success: true, message: response.message || '登录成功' }
        }
        
        return { success: false, message: response?.message || '登录失败' }
      } catch (error) {
        console.error('登录错误:', error)
        return { success: false, message: error.message || '登录失败，请重试' }
      }
    },
    
    logout() {
      this.isAuthenticated = false
      this.user = null
      this.token = null
      this.mqttConfig = null
      
      // 清除localStorage
      localStorage.removeItem(authConfig.tokenKey)
      localStorage.removeItem('user_info')
      localStorage.removeItem('mqtt_config')
    },
    
    checkAuth() {
      const token = localStorage.getItem(authConfig.tokenKey)
      const userInfo = localStorage.getItem('user_info')
      const mqttConfig = localStorage.getItem('mqtt_config')
      
      if (token && userInfo) {
        try {
          this.isAuthenticated = true
          this.token = token
          this.user = JSON.parse(userInfo)
          if (mqttConfig) {
            this.mqttConfig = JSON.parse(mqttConfig)
          }
          return true
        } catch (error) {
          this.logout()
          return false
        }
      }
      
      return false
    },
    
    updateUserInfo(userInfo) {
      this.user = { ...this.user, ...userInfo }
      localStorage.setItem('user_info', JSON.stringify(this.user))
    }
  }
})